package com.example.chapter10;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo9 {
    public static void main(String[] args) {
        String text = "Hello world, hello Java, hello collections.";

        // 1: 将文本拆分为单词数组
        String[] words = text.split("\\s+");

        // 2: 使用Map存储单词及其出现次数
        Map<String, Integer> wordCountMap = new HashMap<>();

        // 3: 遍历单词数组，更新Map中单词出现的次数
        for (String word : words) {
            word = word.replaceAll("[^a-zA-Z]", "").toLowerCase(); // 去除非字母字符并转为小写
            if (!word.isEmpty()) {
                wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);
            }
        }

        // 4: 将Map按照值（出现次数）降序排列
        List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(wordCountMap.entrySet());
        sortedEntries.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        // 5: 输出排序后的结果
        for (Map.Entry<String, Integer> entry : sortedEntries) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
